<?
require 'database.php';
$db = new DB();

$Qry = 'SELECT g.id, g.image
		FROM games g
		WHERE image_up IS NULL
		ORDER BY g.id DESC
		LIMIT 10';

$res = $db->fetchAll($Qry);

foreach ($res as $key=>$value) {
	$imgurl = $value['image'];
	$imagename = basename($imgurl);

	$path = $_SERVER['DOCUMENT_ROOT'] . '/images/games/';

	if (file_exists($path . $imagename)) {
		continue;
	}
	$image = getimg($imgurl);
	file_put_contents($path . $imagename, $image);

	$query = 'UPDATE games SET image_up = "' . $imagename . '", image = "" WHERE id = ' . $value['id'];
	$newIMG = $db->Query($query);

	if ($newIMG)
		echo $key . ' - ' . $value['image'] . '<br />';
}

function getimg($url) {
	$headers[] = 'Accept: image/gif, image/x-bitmap, image/jpeg, image/pjpeg';
	$headers[] = 'Connection: Keep-Alive';
	$headers[] = 'Content-type: application/x-www-form-urlencoded;charset=UTF-8';
	$user_agent = 'php';
	$process = curl_init($url);
	curl_setopt($process, CURLOPT_HTTPHEADER, $headers);
	curl_setopt($process, CURLOPT_HEADER, 0);
	curl_setopt($process, CURLOPT_USERAGENT, $user_agent);
	curl_setopt($process, CURLOPT_TIMEOUT, 30);
	curl_setopt($process, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($process, CURLOPT_FOLLOWLOCATION, 1);
	$return = curl_exec($process);
	curl_close($process);
	return $return;
}